﻿/// <reference path="../../jquery/jquery-1.3.2-vsdoc.js" />
/// <reference path="../Complaint.Namespaces.js" />
/// <reference path="../Complaint.Common.js" />

var oldTitle = "";

$(function() {
    $("#categoryTree").tree(
        {
            lang: {
                new_node: "New category",
                loading: "Loading ..."
            },
            callback: {
                beforerename: function(NODE, LANG, TREE_OBJ) { oldTitle = $(NODE).children("a:eq(0)").text(); return true; },
                beforedelete: function(NODE) {
                    if ($(NODE).children("ul").length > 0) {
                        alert("This category has got sub-categories, please delete sub-categories first.");
                        return false;
                    }
                    return true;
                },
                onrename: save,
                ondelete: del
            }
        });
});

function save(NODE) {
    var parentNode = $(NODE).parents("li:eq(0)").get(0);
    var parentId = parentNode ? parentNode.id : null;
    var newTitle = $(NODE).children("a:eq(0)").text();

    // Create
    if (NODE.id == "")
        $.post(
                    Complaint.Common.AdminRoot + "/Category/Add",
                    {
                        parentID: parentId,
                        Title: newTitle,
                        Status: "True"
                    },
                    function(data) {
                        //$("#grid").html(data);
                        NODE.id = data.id;
                    },
                    "json"
                );
    // Edit
    else if ($.trim(oldTitle) != $.trim(newTitle))
        $.post(
                    Complaint.Common.AdminRoot + "/Category/Edit",
                    {
                        CategoryID: NODE.id,
                        Title: newTitle,
                        Status: "True"
                    }
                );
}

function del(NODE) {
    $.post(
                Complaint.Common.AdminRoot + "/Category/Delete",
                {
                    id: NODE.id
                }
            );
}